import { Context } from 'koishi'
import { UUID } from "uuidjs"
import { defaultUserInfo } from "../utils/defaultData";
import dayjs from "dayjs";
import { levelData } from "../utils/levelData";
import { getSunLimitTime, formatTimeSecondToHMS, recalculateSunInfo } from "../utils/util";
import AllPlantList from "../utils/plantList";


// 检测用户是否已经存在
const checkUserExist = async (ctx: Context, userId: string) => {
    const users = await ctx.database.get('userList', { userId })
    return users && users.length ? users[0] : false
}

// 删除所有用户
const deleteAllUser = async (ctx: Context) => {
    await ctx.database.drop('userList')
}

// 删除所有植物
const deleteAllPlant = async (ctx: Context, userId: string) => {
    await ctx.database.set('userList', { userId }, { plant: [] })
}

// 创建用户
const createUser = async (ctx: Context, messageData: any) => {
    const name = messageData.user.name
    const userId = messageData.user.id
    const avatar = messageData.user.avatar
    if (!name || !userId || !avatar) return null
    // 在数据库中创建用户列表
    const userInfo = {
        id: UUID.generate(),
        name,
        userId,
        avatar,
        userInfo: defaultUserInfo(),
        plant: [],
    }
    await ctx.database.create('userList', userInfo)
    return userInfo
}

// 获取用户信息
const getUserInfo = async (ctx: Context, userId: string) => {
    const users = await ctx.database.get('userList', { userId })
    return users && users.length ? users[0] : null
}

// 获取用户信息 并格式化
const getUserInfoFormat = async (ctx: Context, userId: string) => {
    // let result = `${targetUser.name}的花园\n阳光池：${targetUser.data.sunTotal}\n可收获阳光：${targetUser.data.sun} / ${maxSun}${hasSunReservoir}\n当前等级：${targetUser.data.level}（${levelList[levelIndex].name}）\n持有金币：${targetUser.data.money}\n阳光产出频率：${userSunDropRate}\n阳光产出量：${userSunDropAmount}${plantLimit}\n距离升级还需经验：${needExp}\n下次收获阳光时间：\n${nextSunDropTime}${sunFullNeedTimeStr}${signTip}${protectEndTimeTip}${weatherTip}${isBattlingTip}`
    const info = await getUserInfo(ctx, userId)
    const levelName = levelData().find(i => i.level == info.userInfo.level)?.name
    const needExp = levelData().find(i => i.level == info.userInfo.level)?.exp - info.userInfo.exp
    const sunLimitTime = getSunLimitTime(info.userInfo.sun, info.userInfo.maxSun, info.userInfo.sunNextDropTime, info.userInfo.sunDropTime, info.userInfo.sunDropCount)
    const sunLimitTimeFormat = formatTimeSecondToHMS(sunLimitTime)
    let result = [
        `${info.name}的花园`,
        `阳光池：${info.userInfo.sunTotal}`,
        `可收获阳光：${info.userInfo.sun} / ${info.userInfo.maxSun}`,
        `当前等级：${info.userInfo.level}（${levelName}）`,
        `持有金币：${info.userInfo.money}`,
        `阳光生产时间：${info.userInfo.sunDropTime}`,
        `阳光生产量：${info.userInfo.sunDropCount}`,
        `距离升级还需经验：${needExp}`,
        `下次收获阳光时间：${info.userInfo.sunNextDropTime}`,
        sunLimitTime <= 0 ? '阳光已达到上限 赶紧来收获吧！' : `阳光收集达到上限还需要：${sunLimitTimeFormat}`
    ]
    result = result.map(i => i + '\n')
    return result.join('')
}

// 收获阳光
const harvestSun = async (ctx: Context, userId: string) => {
    const info = await getUserInfo(ctx, userId)
    if (info.userInfo.sun >= info.userInfo.maxSun) {
        // 阳光已达到上限 收取阳光后 下次收取阳光时间重置
        info.userInfo.sunNextDropTime = dayjs().add(info.userInfo.sunDropTime, 'second').format('YYYY-MM-DD HH:mm:ss')
    }
    if (info.userInfo.sun > 0) {
        let harvestSunNumber = info.userInfo.sun
        info.userInfo.sunTotal += info.userInfo.sun
        info.userInfo.sun = 0
        await ctx.database.set('userList', info.id, { userInfo: info.userInfo })
        // 记录更改数据库
        ctx.database.create('dataUpdate', {
            id: UUID.generate(),
            data: {
                sunTotal: info.userInfo.sunTotal,
                getSun: harvestSunNumber
            },
            time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            info: `用户收获阳光：${harvestSunNumber} 用户名：` + info.name
        })
        return {
            harvestSunNumber,
            sunTotal: info.userInfo.sunTotal,
        }
    }
    return {
        harvestSunNumber: 0,
    }
}

// 种植植物
const handlePlant = async (ctx: Context, userId: string, number: number, plantId: number) => {
    const info = await getUserInfo(ctx, userId)
    const targetPlant = AllPlantList().find(i => i.id == plantId)
    const plantList = info.plant
    for (let index = 0; index < number; index++) {
        plantList.push(targetPlant)
    }
    const resultUserInfo = recalculateSunInfo(info.userInfo, plantList)
    await ctx.database.set('userList', info.id, { plant: plantList, userInfo: resultUserInfo })
    // 记录更改数据库
    ctx.database.create('dataUpdate', {
        id: UUID.generate(),
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        info: `用户种植${targetPlant.name}${number}个 用户名：` + info.name
    })
}

// 定时任务 - 用户阳光产出
const userSunDrop = async (ctx: Context) => {
    const userList = await ctx.database.get('userList', {})
    for (let i = 0; i < userList.length; i++) {
        const user = userList[i]
        // 用户阳光未到上限
        if (user.userInfo.sun < user.userInfo.maxSun) {
            // 当前经过收获阳光时间
            const hasSunDrop = dayjs().isAfter(dayjs(user.userInfo.sunNextDropTime, 'YYYY-MM-DD HH:mm:ss'))
            if (hasSunDrop) {
                // 收获阳光
                user.userInfo.sun += user.userInfo.sunDropCount
                // 不超过上限
                user.userInfo.sun = user.userInfo.sun > user.userInfo.maxSun ? user.userInfo.maxSun : user.userInfo.sun
                // 更新下次收获阳光时间
                user.userInfo.sunNextDropTime = dayjs().add(user.userInfo.sunDropTime, 'second').format('YYYY-MM-DD HH:mm:ss')
                // 更新数据库
                await ctx.database.set('userList', user.id, { userInfo: user.userInfo })
                // 记录更改数据库
                ctx.database.create('dataUpdate', {
                    id: UUID.generate(),
                    data: {
                        sunNextDropTime: user.userInfo.sunNextDropTime,
                        sun: user.userInfo.sun
                    },
                    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    info: '用户阳光产出 用户名：' + user.name
                })
            }
        }
    }
}

export {
    checkUserExist,
    createUser,
    getUserInfo,
    getUserInfoFormat,
    harvestSun,
    userSunDrop,
    deleteAllUser,
    handlePlant,
    deleteAllPlant,
}